// 定义最大堆类
class Heap {
    constructor() {
        this.list = [];
    }
    // 获取堆的大小
    size() {
        return this.list.length;
    }
    // 交换数组中两个元素的位置
    swap(i, j) {
        [this.list[i], this.list[j]] = [this.list[j], this.list[i]];
    }
    // 向上调整堆
    heapifyUp() {
        let index = this.list.length - 1;
        while (index > 0) {
            let parentIndex = Math.floor((index - 1) / 2);
            if (this.list[parentIndex] >= this.list[index]) break;
            this.swap(parentIndex, index);
            index = parentIndex;
        }
    }
    // 向下调整堆
    heapifyDown() {
        let index = 0;
        const length = this.list.length;
        while (true) {
            let leftChildIndex = 2 * index + 1;
            let rightChildIndex = 2 * index + 2;
            let largestIndex = index;
            if (leftChildIndex < length && this.list[leftChildIndex] > this.list[largestIndex]) {
                largestIndex = leftChildIndex;
            }
            if (rightChildIndex < length && this.list[rightChildIndex] > this.list[largestIndex]) {
                largestIndex = rightChildIndex;
            }
            if (largestIndex === index) break;
            this.swap(index, largestIndex);
            index = largestIndex;
        }
    }
    // 向堆中插入元素
    push(value) {
        this.list.push(value);
        this.heapifyUp();
    }
    // 从堆中移除并返回最大值
    pop() {
        if (this.list.length === 0) return null;
        if (this.list.length === 1) return this.list.pop();
        const max = this.list[0];
        this.list[0] = this.list.pop();
        this.heapifyDown();
        return max;
    }
    // 获取堆中的最大值
    peek() {
        return this.list.length > 0 ? this.list[0] : null;
    }
}

function scheduleCourse(courses) {
    const courseHeap = new Heap();
    let sum = 0;
    courses.sort((a, b) => a[1] - b[1]);
    courses.forEach(([duration, last_day]) => {
        if (sum + duration <= last_day) {
            sum += duration;
            courseHeap.push(duration);
        } else if (courseHeap.size() > 0 && duration < courseHeap.peek()) {
            sum = sum - courseHeap.pop() + duration;
            courseHeap.push(duration);
        }
    });
    return courseHeap.size();
}